<?php
namespace App\Api;

use PhalApi\Api;
use function PhalApi\DI;

/**
 * 上传
 */

class Upload extends Api {

	public function getRules() {
        return array(
            'upload' => [
                'file' => array('name' => 'file', 'type' => 'file', 'desc' => '上传文件'),
//                'type' => ['name' => 'type', 'type' => 'string', 'desc' => '上传类型']
            ]

        );
	}
	
	/**
     * 七牛Token
     * @desc 用于获取七牛云存储上传使用的Token
     * @return int code 操作码，0表示成功
     * @return array info 
     * @return string info[0].token 七牛Token
     * @return string msg 提示信息
     */
	public function getQiniuToken(){
	
	   	$rs = array('code' => 0, 'msg' => '', 'info' =>array());
        
        
		$configpri=\App\getConfigPri();
		
		$token='';
        switch ($configpri['cloudtype']) {
            case '1':
                $token = \PhalApi\DI()->qiniu->getToken();
                break;

            case '2':
                $token="";
                break;
         } 
		
		

		$rs['info'][0]['token']=$token; 
		return $rs; 
		
	}

	/**
     * 获取云存储方式、获取七牛上传验证token字符串、获取腾讯云存储相关配置信息
     * @desc 用于获取云存储方式、获取七牛上传验证token字符串、获取腾讯云存储相关配置信息
     * @return int code 操作码，0表示成功
     * @return string msg 提示信息
     * @return array info 返回信息
     */
    public function getCosInfo(){

        $rs=array("code"=>0,"msg"=>"","info"=>array());

        //获取七牛信息
        $qiniuToken=$this->getQiniuToken();

        //获取腾讯云存储配置信息
		$configpri=\App\getConfigPri();

        if(!$configpri['cloudtype']){
            $rs['code']=1001;
            $rs['msg']="无指定存储方式";
            return $rs;
        }
		$space_host= \PhalApi\DI()->config->get('app.Qiniu.space_host');
		$region= \PhalApi\DI()->config->get('app.Qiniu.region');
		
		//七牛云存储区域 华东：z0，华北：z1，华南：z2，北美：na0，东南亚：as0，参考文档：https://developer.qiniu.com/kodo/manual/1671/
		$qiniu_zone='';
		if($region=='z0'){
			$qiniu_zone='qiniu_hd';
		}else if($region=='z1'){
			$qiniu_zone='qiniu_hb';
		}else if($region=='z2'){
			$qiniu_zone='qiniu_hn';
		}else if($region=='na0'){
			$qiniu_zone='qiniu_bm';
		}else if($region=='as0'){
			$qiniu_zone='qiniu_xjp';
		}

        $qiniuInfo=array(
            'qiniuToken'=>$qiniuToken['info'][0]['token'],
            'qiniu_domain'=>$space_host,
            'qiniu_zone'=>$qiniu_zone  //华东:qiniu_hd 华北:qiniu_hb  华南:qiniu_hn  北美:qiniu_bm   新加坡:qiniu_xjp 不可随意更改，app已固定好规则
        );

        $awsInfo=array(
            'aws_bucket'=>$configpri['aws_bucket'],
            'aws_region'=>$configpri['aws_region'],
            'aws_identitypoolid'=>$configpri['aws_identitypoolid'],
        );
        
        $rs['info'][0]['qiniuInfo']=$qiniuInfo;
        $rs['info'][0]['awsInfo']=$awsInfo;

        $cloudtype="";
        switch ($configpri['cloudtype']) {
            case '1':
                $cloudtype="qiniu";
                break;

            case '2':
                $cloudtype="aws";
                break;
         } 

        $rs['info'][0]['cloudtype']=$cloudtype;
        
        return $rs;
        
    }
    
    public function uploadFiles()
    {
        $res = [];
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $params = $_POST;
            if (empty($_FILES)) {
                return ['code' => -1, 'msg' => \PhalApi\T('请上传文件')];
            }
            $fileArr = $_FILES['file'];



            // 获取上传配置
            $option = DI()->notorm->option->where("option_name='configpri'")->fetchOne();
            if ($option) {
                $config = json_decode($option['option_value'],true);
                $cloudType = $config['cloudtype'];
                if($cloudType=="1") { //七牛云存储
                    $resData = [];
                    for ($i=0;$i<count($fileArr);$i++) {
                        $url = DI()->qiniu->uploadFile($fileArr[$i]['tmp_name']);
                        $resData[] = $url;
                    }
//                    $url = DI()->qiniu->uploadFile($file['tmp_name']);
                    return array(
                        'code' => 0,
                        'data' => $resData,
                        'msg' => '上传成功'
                    );
                }else if ($cloudType == '2') {
                    // aws 上传
                    require_once ('/www/wwwroot/mangers.flami.live/phalapi/sdk/aws/aws-autoloader.php');
                    $resData = [];
                    for ($i=0;$i<count($fileArr['name']);$i++) {
                        $type = $fileArr['type'][$i];
                        $tmp_name = $fileArr['tmp_name'][$i];
                        $rand=rand(0,100000);
                        if ($type == 'video/mp4') {
                            $name = time().$rand.'.mp4';
                        }else {
                            $name = time().$rand.'.jpg';
                        }
                        $sharedConfig = [
                            'profile' => 'default',
                            'region' => $config['aws_region'], //区域
                            'version' => 'latest',
                            'Content-Type' => $type,
                            //'debug'   => true
                        ];
                        $sdk = new \Aws\Sdk($sharedConfig);
                        $s3Client = $sdk->createS3();

                        $result = $s3Client->putObject([
                            'Bucket' => $config['aws_bucket'],
                            'Key' => $name,
                            'ACL' => 'public-read',
                            'Content-Type' => $type,
                            'Body' => fopen($tmp_name, 'r')
                        ]);
                        $a = (array)$result;
                        $n = 0;
                        foreach($a as $k =>$t){
                            if($n==0){
                                $n++;
                                $info = $t['ObjectURL'];
                                if($info){
                                    // return $info;
                                    $resData[] = [
                                        'url' => \PhalApi\DI()->config->get('app.Aws.space_host') . '/'.$name,
                                        'path' => '/'.$name
                                    ];
                                }
                            }
                        }
                    }

                    return [
                        'code' => 0,
                        'data' => $resData,
                        'msg' => '上传成功'
                    ];
                }
        //
            }
        }

        // 获取上传配置
//        $option = DI()->notorm->option->where("option_name='configpri'")->fetchOne();
//        if ($option) {
//            $config = json_decode($option['option_value'],true);
//            $cloudType = $config['cloudtype'];
//            if($cloudType=="1") { //七牛云存储
//                DI()->qiniu->uploadFile();
//
//            }else {
//
//            }
//
//        }
//
//
//        require_once('');




    }
    
    
}
